<template>
  <div>
    <table class="table table-bordered table-vertical-middle text-center" v-loading="loading">
      <thead>
        <tr>
          <th>序号</th>
          <th class="text-left">报表名</th>
          <th>报表说明</th>
          <th>
            <span>季度</span>
            <el-date-picker
              class="text-year-picker"
              v-model="yearDate"
              type="year"
              :clearable="false"
              prefix-icon="el-icon-caret-bottom"
              format="(yyyy年)"
              placeholder="选择年"
              @change="setQuarterDisabled"
            ></el-date-picker>
          </th>
          <th>新增</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="report in tableData" :key="report.index">
          <td>{{ report.index }}</td>
          <td class="text-left">{{ report.name }}</td>
          <td class="text-left">{{ report.desc }}</td>
          <td>
            <ul class="list-inline">
              <li class="list-inline-item" v-for="(di, j) in report.disabled" :key="`q-${j}`">
                <el-button
                  type="text"
                  :class="di ? 'text-muted' : ''"
                  :disabled="di"
                  @click="handleView(report.index, j + 1)"
                >
                  {{ enumQuarter[j + 1] }}季度
                </el-button>
              </li>
            </ul>
          </td>
          <td>
            <el-tooltip class="item" effect="dark" placement="bottom" :disabled="!addDisabled">
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(report.index)"
              ></el-button>
              <div slot="content">
                <span>1、只能由报表管理员新增</span>
                <br />
                <span>2、只能在下季度第一个月10号前新增</span>
              </div>
            </el-tooltip>
          </td>
        </tr>
      </tbody>
    </table>

    <quarter-report-city-dialog
      :visible.sync="cityVisible"
      :query-year="cityYear"
      :query-quarter="cityQuarter"
    ></quarter-report-city-dialog>

    <quarter-report-org-dialog
      :visible.sync="orgVisible"
      :query-date="orgQueryDate"
    ></quarter-report-org-dialog>

    <quarter-report-finance-dialog
      :visible.sync="financeVisible"
      :query-date="financeQueryDate"
    ></quarter-report-finance-dialog>

    <quarter-report-credit-dialog
      :visible.sync="creditVisible"
      :query-date="creditQueryDate"
    ></quarter-report-credit-dialog>

    <quarter-report-covid-dialog
      :visible.sync="covidVisible"
      :query-date="covidQueryDate"
    ></quarter-report-covid-dialog>

    <quarter-report-effect-dialog
      :visible.sync="effectVisible"
      :query-date="effectQueryDate"
    ></quarter-report-effect-dialog>

    <quarter-report-bank-dialog
      :visible.sync="bankVisible"
      :query-date="bankQueryDate"
    ></quarter-report-bank-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumQuarter, isQuarterDisabled } from '@/credit/views/city/report/reportMixins'

import QuarterReportCityDialog from '@/credit/views/city/report/QuarterReportCityDialog'
import QuarterReportOrgDialog from '@/credit/views/city/report/QuarterReportOrgDialog'
import QuarterReportFinanceDialog from '@/credit/views/city/report/QuarterReportFinanceDialog'
import QuarterReportCreditDialog from '@/credit/views/city/report/QuarterReportCreditDialog'
import QuarterReportCovidDialog from '@/credit/views/city/report/QuarterReportCovidDialog'
import QuarterReportEffectDialog from '@/credit/views/city/report/QuarterReportEffectDialog'
import QuarterReportBankDialog from '@/credit/views/city/report/QuarterReportBankDialog'

const date = new Date()
const currentYear = date.getFullYear()
const currentQuarter = Math.ceil((date.getMonth() + 1) / 3)

export default {
  components: {
    QuarterReportCityDialog,
    QuarterReportOrgDialog,
    QuarterReportFinanceDialog,
    QuarterReportCreditDialog,
    QuarterReportCovidDialog,
    QuarterReportEffectDialog,
    QuarterReportBankDialog,
  },
  props: {},
  data() {
    return {
      loading: false,

      yearDate: date,
      enumQuarter,
      tableData: [
        {
          index: 1,
          name: 'G1县级业务台账',
          desc: '统计业务发生区县情况(只针对有业务发生区县)，季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 2,
          name: 'G2机构及人员统计表',
          desc: '统计公司渠道建设情况,季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 3,
          name: 'G3财政支持政策统计表',
          desc: '统计农担公司获得财政政策支持情况．季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 4,
          name: 'G4政担合作情况统计表',
          desc: '统计与各级政府业务合作情况.季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 5,
          name: 'G5疫情期间各项扶农惠农举措落实情况统计表',
          desc: '统计农担公司扶农惠农举措落实情况（在疫情期间),季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 6,
          name: 'G6省级农担公司社会效应统计表',
          desc: '统计农担通过支持产业,在脱贫攻坚和带动就业方面的成效，季末下月10日前报送',
          disabled: [false, false, false, false],
        },
        {
          index: 7,
          name: 'G7银担合作情况统计表',
          desc: '统计与各银行的业务发生情况.季末下月10日前报送',
          disabled: [false, false, false, false],
        },
      ],

      queryDate: date,

      cityYear: currentYear,
      cityQuarter: currentQuarter,
      cityVisible: false,
      lastYear: -1,
      lastQuarter: -1,

      orgQueryDate: date,
      orgVisible: false,

      financeQueryDate: date,
      financeVisible: false,

      creditQueryDate: date,
      creditVisible: false,

      covidQueryDate: date,
      covidVisible: false,

      effectQueryDate: date,
      effectVisible: false,

      bankQueryDate: date,
      bankVisible: false,
    }
  },
  computed: {
    ...mapGetters(['user']),
    addDisabled() {
      const date = new Date()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return this.user.isReporter !== 1 || ![1, 4, 7, 10].includes(month) || day > 10
    },
  },
  watch: {},
  created() {
    this.setQuarterDisabled()
  },
  mounted() {},
  methods: {
    setQuarterDisabled() {
      const year = this.yearDate.getFullYear()
      this.tableData.forEach(it => {
        const disabled = []
        for (let i = 0; i < 4; i++) {
          disabled[i] = isQuarterDisabled(year, i + 1)
        }
        it.disabled = disabled
      })

      this.getCityReport()
    },
    handleView(reportIndex, quarterIndex) {
      const queryDate = new Date(this.queryDate.getFullYear(), quarterIndex * 3)
      switch (reportIndex) {
        case 1:
          this.cityYear = this.queryDate.getFullYear()
          this.cityQuarter = quarterIndex
          this.cityVisible = true
          break
        case 2:
          this.orgQueryDate = queryDate
          this.orgVisible = true
          break
        case 3:
          this.financeQueryDate = queryDate
          this.financeVisible = true
          break
        case 4:
          this.creditQueryDate = queryDate
          this.creditVisible = true
          break
        case 5:
          this.covidQueryDate = queryDate
          this.covidVisible = true
          break
        case 6:
          this.effectQueryDate = queryDate
          this.effectVisible = true
          break
        case 7:
          this.bankQueryDate = queryDate
          this.bankVisible = true
          break
        default:
          break
      }
    },

    handleAdd(reportIndex) {
      if (this.addDisabled) {
        return // this.$message.error('不能新增报表')
      }
      if (reportIndex === 1) {
        this.loading = true
        this.getLastCityReport()
          .then(res => {
            if (res) {
              let { year, quarter } = res
              if (currentYear > year || currentQuarter > quarter) {
                quarter++
                if (quarter > 4) {
                  quarter = 1
                  year++
                }
              }
              this.cityYear = year
              this.cityQuarter = quarter

              this.cityVisible = true
            } else {
              this.$message.error('获取上季度报表失败，不能新增报表')
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.queryDate = date
        this.handleView(reportIndex, currentQuarter)
      }
    },

    getCityReport(year) {
      this.loading = true
      return this.$api
        .getData(this.$serviceName, 'report_quarter', {
          'year_number.lte': year,
          'year_number.gte': year - 1,
          fields: ['year_number', 'quarter_number'],
        })
        .then(res => {
          const data = res.data || []
          const { disabled } = this.tableData[0]

          // 第一季度，看上一年第四季度是否已创建
          if (!disabled[0]) {
            const preYearLastQuarter = data.find(
              it => +it.year_number === year - 1 && +it.quarter_number === 4
            )
            if (!preYearLastQuarter) {
              disabled[0] = true
            }
          }

          // 其余看当前年上一季度是否创建
          for (let i = 2; i < 5; i++) {
            if (!disabled[0]) {
              const quarter = data.find(
                it => +it.year_number === year && +it.quarter_number === i - 1
              )
              if (!quarter) {
                disabled[0] = true
              }
            }
          }

          this.tableData[0].disabled = disabled
        })
        .finally(() => {
          this.loading = false
        })
    },

    getLastCityReport() {
      return this.$api
        .getData(
          this.$serviceName,
          'report_quarter',
          {
            index: 1,
            size: 1,
            fields: ['year_number', 'quarter_number'],
          },
          {
            year_number: 'desc',
            quarter_number: 'desc',
          }
        )
        .then(res => {
          const list = (res && res.data && res.data.data) || []
          const data = list && list.length && list[0]
          return data
            ? {
                year: +data.year_number,
                quarter: +data.quarter_number,
              }
            : null
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.text-year-picker {
  width: 82px;
  /deep/ .el-input__inner {
    border: none;
    padding: 0 2px;
    &:focus {
      box-shadow: none;
    }
  }
  /deep/ .el-input__prefix {
    left: auto;
    right: 5px;
  }
}
</style>
